package com.zjhn.ds.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zjhn.ds.common.Constant;
import com.zjhn.ds.common.annotate.IgnoreTenant;
import com.zjhn.ds.domain.entity.jlw.Station;
import com.zjhn.ds.domain.entity.jlw.WorkshopClasses;
import com.zjhn.ds.domain.vo.StationDurationRecordVo;
import com.zjhn.ds.domain.vo.StationStatusVo;
import com.zjhn.ds.mapper.StationMapper;
import com.zjhn.ds.utils.CommonUtil;
import com.zjhn.ds.utils.RestHighLevelUtils;
import com.zjhn.ds.utils.base.DateUtil;
import com.zjhn.ds.utils.base.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: ds_jlw
 * @BelongsPackage: com.zjhn.ds.task
 * @Author: sxt
 * @CreateTime: 2023-12-20  08:49
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Configuration
public class StationDurationRecordTask {

    @Resource
    private CommonUtil commonUtil;

    @Resource
    private RedisCache redisCache;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private RestHighLevelUtils restHighLevelUtils;


    @IgnoreTenant
    @Scheduled(fixedDelay = 1000 * 60)
    public void statics() {
        long start = System.currentTimeMillis();
        log.info("====[INFO]====StationDurationRecordTask====statics 机台时长记录定时任务触发");
        String workshopId = "523cd11213f4f82407b75880f941ee88";
        // 获取车间机台
        List<Station> stations = stationMapper.selectList(
                new QueryWrapper<Station>()
                        .eq("workshop_id", workshopId));
        // 获取当前班次
        WorkshopClasses currentClass = commonUtil.getWorkshopClasses();
        // 获取当天
        if (currentClass != null) {
            List<JSONObject> list = new ArrayList<>();
            String currentDay = DateUtil.getCurrentDay(currentClass.getStartTime(), currentClass.getEndTime(), new Date());
            try {
                for (Station station : stations) {
                    String equipmentId = commonUtil.getBindInfoById(station.getId());
                    if (StringUtils.isBlank(equipmentId))
                        continue;

                    String macAddress = commonUtil.getEquipmentById(equipmentId).getOutreachDevice();
                    if (StringUtils.isBlank(macAddress))
                        continue;

                    Object lastStatus = redisCache.getCacheObject(Constant.REDIS_PRE.LAST_STATION_STATUS + macAddress);
                    if (lastStatus == null) lastStatus = "0";
                    Object status = redisCache.getCacheObject(Constant.REDIS_PRE.STATION_STATUS + macAddress);
                    if (status == null) status = "0";
                    if (!lastStatus.toString().equals(status.toString())) {
                        log.info("===========xxxxxxxxx===========xxxxxxxxxx========== lastStatus:{}, status:{}", lastStatus, status);
                        // 状态变记录
                        list.add(JSONObject.parseObject(JSON.toJSONString(StationStatusVo.builder()
                                .uuid(IdWorker.get32UUID())
                                .today(DateUtil.formatDateToString(new Date(), DateUtil.DATE_FORMAT))
                                .classBeginTime(currentClass.getStartTime())
                                .classEndTime(currentClass.getEndTime())
                                .stationId(station.getId())
                                .status(status.toString())
                                .createTime(new Date())
                                .build())));
                    }
                    // 设置上次状态
                    redisCache.setCacheObject(Constant.REDIS_PRE.LAST_STATION_STATUS + macAddress, status.toString(), 2 * 60);

                    // 记录机台运行时长
                    String key = Constant.REDIS_PRE.STATION_DURATION_RECORD + currentDay + ":" + currentClass.getId() + ":" + station.getId();
                    Object record = redisCache.getCacheObject(key);
                    StationDurationRecordVo stationDurationRecordVo;
                    if (record == null)
                        stationDurationRecordVo = StationDurationRecordVo.builder()
                                .runTime("0")
                                .idleTime("0")
                                .faultTime("0")
                                .stopTime("0")
                                .build();
                    else
                        stationDurationRecordVo = JSONObject.parseObject(record.toString(), StationDurationRecordVo.class);

                    if ("0".equals(status.toString()))
                        stationDurationRecordVo.setStopTime(String.valueOf(Integer.parseInt(stationDurationRecordVo.getStopTime()) + 1));
                    if ("1".equals(status.toString()))
                        stationDurationRecordVo.setRunTime(String.valueOf(Integer.parseInt(stationDurationRecordVo.getRunTime()) + 1));
                    if ("2".equals(status.toString()))
                        stationDurationRecordVo.setIdleTime(String.valueOf(Integer.parseInt(stationDurationRecordVo.getIdleTime()) + 1));
                    if ("3".equals(status.toString()))
                        stationDurationRecordVo.setFaultTime(String.valueOf(Integer.parseInt(stationDurationRecordVo.getFaultTime()) + 1));

                    redisCache.setCacheObject(key, JSON.toJSONString(stationDurationRecordVo, 10 * 60));
                }
            } catch (Exception e) {
                log.error("====[ERROR]====StationDurationRecordTask====statics 机台时长记录定时任务触发异常 e:{}", e.getMessage());
            }

            if (list.size() > 0)
                // es记录
                restHighLevelUtils.multiAddDoc(Constant.ES_INDEX.STATION_STATUS_RECORD_INDEX, list);
        }
        long end = System.currentTimeMillis();
        log.info("====[INFO]====StationDurationRecordTask====statics 机台时长记录定时任务结束 time:{}ms", end-start);
    }
}
